﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Zhuang.Utility.Common.DataBase;
using Zhuang.Utility.Common.Entity;
using Zhuang.Model.Access;
namespace Zhuang.DAL.Access
{
    public class ProductDAL
    {
        public ProductEntity Get(int id)
        {
            ProductEntity pe = new ProductEntity();
            pe.ProductId = id;

            string strSql = EntityHelper<ProductEntity>.GetSelectSql(pe);

            DataTable dt= OleDbHelper.Query(strSql).Tables[0];

            if (dt.Rows.Count > 0)
            {
                pe = new ProductEntity();

                pe = EntityHelper<ProductEntity>.FillEntity(dt.Rows[0]);

            }
            else
            {
                pe = null;
            }
          
            return pe;
        }

        public DataTable Get(string condition)
        {
            string strSql = @"SELECT a.ProductId,a.ProductCode, a.ProductName, a.BarCode, a.SearchCode, a.Unit,a.RetailPrice,a.MemberPrice,a.WholesalePrice,a.PurchasePrice, a.Status, a.Description, a.CreationDate, a.ModifiedDate
            FROM Product a where a.ProductCode like '%{0}%' or a.ProductName like '%{0}%' or a.BarCode like '%{0}%' or a.SearchCode like '%{0}%' ";
            strSql = string.Format(strSql,condition);
            return OleDbHelper.Query(strSql).Tables[0];
           
        }

        public void Add(ProductEntity product)
        {

            string strSql = EntityHelper<ProductEntity>.GetInsertSql(product);

            OleDbHelper.ExecuteSql(strSql);
        }

        public void Delete(int id)
        {
            ProductEntity pe = new ProductEntity();
            pe.ProductId = id;

            string strSql = EntityHelper<ProductEntity>.GetDeleteSql(pe) ;

            OleDbHelper.ExecuteSql(strSql);
        }

        public void Update(ProductEntity pe)
        {
            string strSql = EntityHelper<ProductEntity>.GetUpdateSql(pe) ;
            OleDbHelper.ExecuteSql(strSql);

        }

        public string GetProductCode()
        {

            string strSql = "select top 1 ProductCode from Product order by ProductCode desc";

            DataTable dt= OleDbHelper.Query(strSql).Tables[0];
            int iProductCode=0;
            if (dt.Rows.Count > 0)
            {
                iProductCode = Convert.ToInt32(dt.Rows[0]["ProductCode"]);
            }

            iProductCode = iProductCode + 1;
            string newProductCode = iProductCode.ToString().PadLeft(6,'0');

            return newProductCode;
            
        }



    }
}
